package com.itheima.app.controller;

import com.itheima.app.manager.UserManager;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import org.apache.catalina.mbeans.UserMBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
public class UserController {

    @Autowired
    private UserManager userManager;

    @PostMapping("/user/save")
    public ResponseEntity save(@RequestBody User user) {

        return userManager.save(user);
    }

    @GetMapping("/user/findByPhone")
    public ResponseEntity findByPhone(String phone) {

        return userManager.findByone(phone);
    }

    @PostMapping("/user/login")
    public void sendSms(@RequestBody Map<String, String> map) {

        String phone = map.get("phone");

        userManager.sendSms(phone);
    }

    @PostMapping("/user/loginVerification")
    public ResponseEntity regAndLogin(@RequestBody Map<String, String> map) {

        String phone = map.get("phone");

        String verificationCode = map.get("verificationCode");

        return userManager.regAndLogin(phone, verificationCode);
    }

    @PostMapping("/user/loginReginfo")
    public void saveUserInfo(@RequestBody UserInfo userInfo, @RequestHeader("Authorization") String token) {
        // 调用manager
        userManager.saveUserInfo(userInfo, token);
    }

  /*  @PostMapping("/user/loginReginfo/head")
    public ResponseEntity saveOrUpdatePhoto(MultipartFile headPhoto, @RequestHeader("Authorization") String token) {

        try {
            return userManager.saveOrUpdatePhoto(headPhoto, token);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }*/

    @GetMapping("/users")
    public ResponseEntity findUserInfoById(@RequestParam(required = false) Long userID, @RequestHeader("Authorization") String token) {

        System.out.println("查询用户信息");

        if (userID != null) {

            return userManager.findUserInfoById(userID);

        } else {

            User user = userManager.findUserByToken(token);

            if (user.getId() == null) {

                return ResponseEntity.status(401).body(null);
            }

            return userManager.findUserInfoById(user.getId());
        }
    }

    @PutMapping("/users")
    public ResponseEntity updateUserInfo(@RequestBody UserInfo userInfo, @RequestHeader("Authorization") String token) {

        return userManager.updateUserInfo(userInfo, token);
    }

    @PostMapping({"/user/loginReginfo/head", "/users/header"})
    public ResponseEntity saveOrUpdatePhoto(MultipartFile headPhoto, @RequestHeader("Authorization") String token) throws IOException {

        return userManager.saveOrUpdatePhoto(headPhoto, token);
    }
}
